<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="试卷名称" prop="paperName">
        <el-input v-model="queryParams.paperName" placeholder="请输入试卷名称" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="试卷分类" prop="paperType">
        <el-select v-model="queryParams.paperType" placeholder="请选择">
          <el-option v-for="dict in paperTypeList" :key="dict.dictCode" :label="dict.dictLabel"
            :value="dict.dictCode"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="试卷状态" prop="paperStatus">
        <el-select v-model="queryParams.paperStatus" placeholder="请选择">
          <el-option label="启用" value="0"></el-option>
          <el-option label="禁用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button class="primaryButton" color="#265DA4" :dark="isDark" icon="Search" @click="handleQuery"
          v-hasPermi="['manager:examinationPaper:query']">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button color="#265DA4" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['manager:examinationPaper:add']">新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="paperList">
      <el-table-column label="序号" align="left" type="index" width="100" />
      <el-table-column label="试卷名称" align="left" prop="paperName" />
      <el-table-column label="试卷分类" align="left" prop="paperTypeName">
      </el-table-column>
      <el-table-column label="试卷等级" align="left" prop="paperLevelName">
      </el-table-column>
      <el-table-column label="试卷状态" align="left" prop="paperStatus">
        <template #default="scope">
          <el-switch style="--el-switch-on-color: #2B5AA2;" v-model="scope.row.paperStatus" :active-value="0"
            :inactive-value="1">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="题目统计" align="left" prop="questionSum">
      </el-table-column>

      <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link style="color:#265DA4;" icon="EditPen" @click="handleDetail(scope.row)"
            v-hasPermi="['manager:paperQuestion:remove']">详情</el-button>
          <el-button link style="color:#265DA4;" icon="Edit" @click="handlePaper(scope.row)"
            v-hasPermi="['manager:examinationPaper:edit']">试卷配置</el-button>
          <el-button link style="color:#265DA4;" v-hasPermi="['manager:examinationPaper:remove']" icon="Delete"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 详情弹框 -->
    <Detail ref="detailDialog" :paperId="paperId" />
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="780px" append-to-body class="dialogClass">
      <template #title>
        <el-icon color="#fff">
          <CollectionTag />
        </el-icon>
        <span>{{ title }}</span>
      </template>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="试卷名称:" prop="paperName">
              <el-input v-model="form.paperName" placeholder="请输入试卷名称" class="inputDeep" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="试卷分类:" prop="paperType">
              <el-select v-model="form.paperType" placeholder="请选择">
                <el-option v-for="dict in paperTypeList" :key="dict.dictCode" :label="dict.dictLabel"
                  :value="dict.dictCode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="试卷等级:" prop="paperLevel">
              <el-select v-model="form.paperLevel" placeholder="请选择">
                <el-option v-for="dict in paperLevelList" :key="dict.dictCode" :label="dict.dictLabel"
                  :value="dict.dictCode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#265DA4" @click="submitForm">确 定</el-button>
          <el-button @click="open = false" color="#265DA4" plain>取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 试卷配置对话框 -->
    <el-dialog title="试卷配置" v-model="openConfig" width="780px" append-to-body class="dialogClass">
      <template #title>
        <el-icon color="#fff">
          <CollectionTag />
        </el-icon>
        <span>试卷配置</span>
      </template>
      <el-form ref="configRef" :model="form" :rules="rules1" label-width="120px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="试卷名称:" prop="paperName">
              <el-input v-model="form.paperName" placeholder="请输入试卷名称" class="inputDeep" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试卷分类:" prop="paperType">
              <el-select disabled v-model="form.paperType" placeholder="请选择">
                <el-option v-for="dict in paperTypeList" :key="dict.dictCode" :label="dict.dictLabel"
                  :value="dict.dictCode"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试卷等级:" prop="paperLevel">
              <el-select disabled v-model="form.paperLevel" placeholder="请选择">
                <el-option v-for="dict in paperLevelList" :key="dict.dictCode" :label="dict.dictLabel"
                  :value="dict.dictCode"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="试卷状态" prop="paperStatus">
              <el-select v-model="form.paperStatus" placeholder="请选择" @change="handleChange">
                <el-option label="启用" value="0"></el-option>
                <el-option label="禁用" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="单项考核配置:" prop="singleExamine">
              <div class="time-box">
                <el-input disabled v-model="form.singleExamine" placeholder="请选择" class="inputDeep" />
                <el-button color="#265DA4" @click="selectType">选择</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div class="itemTitle">
              <span class="title">理论知识考核配置</span>
              <div>
                <el-button color="#265DA4" plain @click="handleAuto">自动匹配</el-button>
                <el-button color="#265DA4" plain @click="handleConfig">权重配置</el-button>
              </div>
            </div>
            <el-row v-for="item in countJSON" :key="item.code">
              <el-col :span="24" class="quesTitle">
                <el-tag type="plain" effect="plain"> {{ item.name }}</el-tag>
              </el-col>
              <el-col :span="8" v-for="itemc in item.data" :key="itemc.dictCode">
                <el-form-item :label="itemc.dictLabel" prop="questionCount">
                  <el-input v-model="itemc.questionCount" type="number" min="0" placeholder="请输入" @input="handleInput"
                    oninput="value=value.replace( '-','')" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div class="itemTitle">
                  <span class="title">实操考试配置</span>
                </div>
              </el-col>
              <el-col :span="24">
                <div class="itemTitle">
                  <el-select v-model="form.train_examine"  popper-class="exam-selct__popper"
                      placeholder="请选择建筑结构">
                      <el-option v-for="item in operationTrainList" :key="item.trainId" :label="item.title"
                          :value="item.trainId" />
                  </el-select>
                </div>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="loadingC" color="#265DA4" @click="submitConfig">确 定</el-button>
          <el-button @click="openConfig = false" color="#265DA4" plain>取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权重配置对话框 -->
    <el-dialog title="权重配置" v-model="openCon" width="780px" append-to-body class="dialogClass">
      <template #title>
        <el-icon color="#fff">
          <CollectionTag />
        </el-icon>
        <span>权重配置</span>
      </template>
      <el-form ref="weightRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="题目总数量:" prop="scaleQuestionCount">
              <el-input v-model="form.scaleQuestionCount" placeholder="请输入" class="inputDeep" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <div class="itemTitle">
              <span class="title">权重总计：{{ scaleSum }}%</span>
              <el-text class="mx-1" color="#265DA4">权重占比配置参考来源</el-text>
            </div>
            <el-row>
              <el-table border :data="countJSONScale" :summary-method="getSummaries">
                <el-table-column label="题目" align="left" prop="name">
                </el-table-column>
                <el-table-column label="占比" align="left" prop="data">
                  <template #default="scope">
                    <el-input v-model="scope.row.data"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#265DA4" @click="submitScale">确 定</el-button>
          <el-button @click="openCon = false" color="#265DA4" plain>取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 单项考核配置选择 -->

    <el-dialog title="考核选择" v-model="openCheck" width="780px" append-to-body>
      <div v-for="dict in toolList" :key="dict.toolLevel">
        <h3>{{ dict.toolName }}</h3>
        <el-button color="#265DA4" @click="handleSelection">确定</el-button>
        <el-table :data="dict.toolData" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="left" />
          <el-table-column label="工具ID" align="left" prop="toolId" />
          <el-table-column label="工具名称" align="left" prop="toolName" />
          <!-- <el-table-column label="操作" align="left" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link style="color:#265DA4;" @click="selectItem(scope.row)">选择</el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Place">
import JSONbig from 'json-bigint'
import { ElMessage, ElMessageBox } from "element-plus";
import Detail from "./Dialog/detail";
import {
  examinationPaperList,
  examinationPaperAdd,
  examinationPaperDetail,
  examinationPaperEdit,
  examinationPaperRomove,
  scaleDetail,
  scaleEdit,
  autoMatch
} from "@/api/examManage/examPaper";
import { knowledgeLibraryList } from "@/api/knowledge/library";
import { listData } from "@/api/system/dict/data";
import { gettoolManager } from "@/api/manage/manage";
import { listOperationTrain } from "@/api/manage/operationTrain";
const { proxy } = getCurrentInstance();

const examPerList = ref([]);
const paperList = ref([]);
const open = ref(false);
const openConfig = ref(false);
const openCon = ref(false);
const loading = ref(true);
const loadingC = ref(false);
const single = ref(true);
const openCheck = ref(false);
const total = ref(0);
const title = ref("");
const knowList = ref([]);
const paperTypeList = ref([]);
const paperLevelList = ref([]);
const toolList = ref([]);
const countJSON = ref({});
const countJSONScale = ref([]);
const configData = ref({});
const scaleSum = ref(100);
const paperTopicList = ref([]);
const detailDialog = ref(null);
const paperId = ref("");
const seleTool = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageSize: 10,
    pageNum: 1,
    paperName: "",
    paperType: "",
    paperStatus: "",
  },
  rules: {
    paperName: [
      { required: true, message: "考点名称不能为空", trigger: "blur" },
    ],
  },
  rules1: {
    singleExamine: [
      { required: true, message: "单项考核工具不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules, rules1 } = toRefs(data);

console.log(queryParams.value, "value");

// 获取考核配置
function gettoolList() {
  gettoolManager({
    pageSize: 1000,
    pageNum: 1,
  }).then((response) => {
    console.log(response, "response");
    toolList.value = response;
  });
}
// 试卷分类
function getPaperType() {
  listData({
    pageNum: 1,
    pageSize: 100,
    dictType: "sys_paper_type",
  }).then((response) => {
    paperTypeList.value = response.rows;
  });
}
// 试卷等级
function getPaperLevel() {
  listData({
    pageNum: 1,
    pageSize: 100,
    dictType: "sys_paper_level",
  }).then((response) => {
    paperLevelList.value = response.rows;
  });
}
/** 查询试卷列表 */
function getList() {
  loading.value = true;
  examinationPaperList(queryParams.value).then((response) => {
    paperList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

const operationTrainList = ref([])
// 查询实操配置列表
function getOperationTrainList() {
  listOperationTrain().then(res => {
    console.log(res);
    operationTrainList.value = res.rows
  })
}
getOperationTrainList()

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  // form.value = {
  //   libIds: "",
  //   typeName: "",
  // };
  proxy.resetForm("noticeRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
// function switchC(row) {
//   console.log(row, "row");
//   let tip = row.status ? "启用" : "禁用";
//   ElMessageBox.alert("确定" + tip + "该数据项吗？", "提示");
// }
// 自动匹配试卷
function handleAuto() {
  // submitConfig();
  autoMatch(form.value.scaleId).then((res) => {
    console.log(res, 'res');

    if (res.code === 200) {
      countJSON.value = JSONbig.parse(res.data).contJson;
      console.log(countJSON.value, 'countJSON.value');
      countJSON.value.forEach((item) => {
        item.code = item.code.toString()
      })
      console.log(countJSON.value, 'countJSON.value');
      ElMessage.success(res.msg)
    }
  }).catch((err) => {
    ElMessage.success(err)
  })
}
function handleConfig() {
  openCon.value = true;
  console.log(countJSON.value, 'countJSON.value');
  getScaleDetail();
}
function handleInput(value) {
  console.log(value, "value");
  value = value.replace(/-/, "0");
}
/** 新增按钮操作 */
function handleAdd() {
  form.value = {};
  open.value = true;
  title.value = "新增";
}
/**试卷配置操作 */
function handlePaper(row) {
  console.log(row, "row");
  openConfig.value = true;
  form.value.scaleId = row.scaleId;
  nextTick(() => {
    form.value.paperName = row.paperName;
    form.value.paperType = row.paperType;
    form.value.paperLevel = row.paperLevel;
    form.value.paperStatus = String(row.paperStatus);

  })
  if (row.singleExamineInfo && row.singleExamineInfo.length > 0) {
    var siginArr = row.singleExamineInfo.map(item => {
      return item.name
    })
  }

  configData.value.singleExamine = row.singleExamine;
  configData.value.paperStatus = form.value.paperStatus;
  configData.value.paperId = row.paperId;
  configData.value.practicalExamine = row.practicalExamine || "123";
  form.value.singleExamine = siginArr.join(',');
  countJSON.value = JSONbig.parse(row.countJson).contJson;
  countJSON.value.forEach((item) => {
    item.code = item.code.toString()
  })
}
function handleChange(value) {
  configData.value.paperStatus = value;
}
// 提交配置操作按钮
function submitConfig() {
  proxy.$refs["configRef"].validate((valid) => {
    if (valid) {
      loadingC.value = true;
      examinationPaperEdit({
        ...configData.value,
        countJson: JSONbig.stringify({
          contJson: countJSON.value,
        }),
      }).then((response) => {
        proxy.$modal.msgSuccess("修改试卷配置成功");
        openConfig.value = false;
        getList();
      }).catch((err) => {

      })
      loadingC.value = false;
    }
  });
}

// 获取权重的列表
function getScaleDetail() {
  scaleDetail(form.value.scaleId).then((response) => {
    let dataJson = response.data;
    console.log(response, "response");
    form.value.scaleQuestionCount = dataJson.scaleQuestionCount;
    countJSONScale.value = JSONbig.parse(dataJson.dataJson);
    // console.log(countJSONScale.value,'countJSONScale.value11');
    countJSONScale.value.forEach((item) => {
      item.code = item.code.toString()
    })
    console.log(countJSONScale.value, 'countJSONScale.value22');
  });
}
// 提交权重按钮
function submitScale() {
  scaleSum.value = 0
  countJSONScale.value.forEach((item) => {
    scaleSum.value += Number(item.data)
  })
  if (Number(scaleSum.value) > 100) {
    proxy.$modal.msgSuccess("权重总计不能超过100%");
    return;
  }
  scaleEdit({
    scaleId: form.value.scaleId,
    scaleQuestionCount: form.value.scaleQuestionCount,
    dataJson: JSONbig.stringify(countJSONScale.value),
  }).then((response) => {
    proxy.$modal.msgSuccess("修改权重配置成功");
    openCon.value = false;
  });
}
// 计算权重总占比
function getSummaries(param) {
  console.log(param, "param");
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    const values = data.map((item) => Number(item[column.property]));
    console.log(values, "values");
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0)}`;
    } else {
      sums[index] = "0";
    }
  });
  scaleSum.value = sums[1];
  console.log(scaleSum.value, 'scaleSum.value');
  return sums;
}
/** 新增提交按钮 */
function submitForm() {
  console.log(form.value, "form.value");
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {
      console.log(form.value, "form.value.");
      examinationPaperAdd(form.value).then((response) => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
  });
}
/** 查看试卷详情 */
function handleDetail(row) {
  console.log(proxy.$refs, "proxy.$refs", detailDialog);
  detailDialog.value.open = true;
  paperId.value = row.paperId;
  detailDialog.value.getList(paperId.value);
}
/** 删除按钮操作 */
function handleDelete(row) {
  const paperId = row.paperId;
  proxy.$modal
    .confirm('是否确认删除分类为"' + row.paperId + '"的数据项？')
    .then(function () {
      return examinationPaperRomove(paperId);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}
// 选择单项考核配置按钮
function selectType() {
  openCheck.value = true;
}
// 单选
function selectItem(row) {
  form.value.singleExamine = row.toolName;
  configData.value.singleExamine = row.toolId;
  openCheck.value = false;
}
// 多选
function handleSelectionChange(data) {
  console.log(data, 'data');
  var toolIds = data.map((item) => {
    return item.toolId
  })
  var toolName = data.map((item) => {
    return item.toolName
  })
  console.log(toolIds, 'toolIds', toolName);
  seleTool.toolIds = toolIds
  seleTool.toolName = toolName
}
function handleSelection(toolIds, toolName) {
  form.value.singleExamine = seleTool.toolName.join(',');
  configData.value.singleExamine = seleTool.toolIds.join(',');
  openCheck.value = false;
}



gettoolList();
getPaperType();
getPaperLevel();
// getLibraryList();
getList();
</script>
<style lang="scss" scoped>
:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #265DA4 !important; //修改默认的背景色
}

.primaryButton {
  background-color: #265DA4 !important;

}

.inputDeep {
  :deep(.el-input__inner) {
    width: 192px !important;
  }
}

.time-box {
  display: flex;
  justify-content: space-between;

  .el-date-editor {
    width: 206px;
  }

  .el-button {
    margin-left: 15px;
  }

}

.itemTitle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px;
  font-size: 15px;

  .title {
    font-weight: bold;
  }

  el-text {
    font-size: 14px;
    color: #409eff;
  }
}

.quescontent {
  min-height: 200px;
  border: 1px solid #ccc;
}

.quesTitle {
  margin: 20px;
}
</style>
